package com.glodon.paas.account.util.captcha1;
 
 

import java.awt.Font;
import java.awt.image.BufferedImage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;

import redis.clients.jedis.Jedis;

import com.glodon.paas.util.UUIDUtil;

/**
 * 验证码服务接口
 * 
 * @author 
 */
public class CaptchaService {
	private static Logger LOGGER = LoggerFactory.getLogger(CaptchaService.class);


	@Autowired
	RedisTemplate<String,String> tgtRedisTemplate;
	@Autowired
	redis.clients.jedis.JedisPool jedisPool;

	// 图片的宽度。
	@Value("${account.captcha.width}")
	private int width = 120;
	// 图片的高度。
	@Value("${account.captcha.height}")
	private int height = 40;
	// 验证码字符个数
	@Value("${account.captcha.codeCount}")
	private int codeCount = 4;
	// 验证码干扰线数
	@Value("${account.captcha.lineCount}")
	private int lineCount = 100;
	// 获取验证码次数
	@Value("${account.captcha.verifyMax}")
	private int verifyMax = 3;
	// 获取验证码字体
	@Value("${account.captcha.fountName}")
	private String fountName = "arial";
	
	
	// UUID
	public String generalCaptchaKey(String userCertificate){
		String key = UUIDUtil.getUUIDStr();
		if(userCertificate!=null){
			return userCertificate + key;
		}
		return key;
	};
	
	public BufferedImage generalCaptcha(String captchakey){
		CaptchaImageGenerator ccode = new CaptchaImageGenerator(width, height, codeCount, lineCount, fountName, Font.PLAIN);
		String value =  ccode.getCode();
		BufferedImage img = ccode.getBuffImg();
		
		saveCaptchaValue(captchakey, value); 		
		return img;
	};

	/**
	 * 验证输入是否正确
	 * 每个key只能比较4次，超过4次清空缓存，并返回null
	 * 
	 * @param captchakey
	 * @param captchaValue
	 * @param isLast
	 * @return
	 */
	public Boolean verifyCaptcha(String captchakey, String captchaValue, boolean isLast){		
		String cachedValue = null;
		// 如果取缓存value出错，为不影响业务，让验证通过
		try {
			cachedValue = getCaptchaValue(captchakey);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(),e);
			return true;
		}
		
		// vacheValue==null表示缓存失效
		if(cachedValue == null){
			return null;
		}
		
		boolean ok = cachedValue.equalsIgnoreCase(captchaValue);
		// 最后一次请求，不管结果如何都要清空缓存
		if(isLast){
			clean(captchakey);
			return ok;
		}

		// 失败超过一定次数，验证码失效
		if(!ok){
			long verifyNum = getVerifyNum(captchakey);
			if(verifyNum > verifyMax){
				clean(captchakey);
				return null;
			} 
		}
		
		return ok;
	};
	 
	int seconds = 120;
	private boolean saveCaptchaValue(String key, String value){
		final Jedis jedis = jedisPool.getResource();
		try{
			jedis.setex(formatCaptchaKey(key), seconds, value);			
		}finally{
			jedisPool.returnResource(jedis);
		}
		return true;
	}
	
	private String getCaptchaValue(String key){
		final Jedis jedis = jedisPool.getResource();
		try{
			return jedis.get(formatCaptchaKey(key));
		}finally{
			jedisPool.returnResource(jedis);
		}
	}
	
	private long getVerifyNum(String captchakey) {
		final Jedis jedis = jedisPool.getResource();
		try{
			return jedis.incr(formatNumberKey(captchakey));
		}catch(Exception e){
			jedis.del(formatNumberKey(captchakey));
			LOGGER.error("jedis.incr() error:\n" + e.getMessage(),e);
		}finally{
			jedisPool.returnResource(jedis);
		}
		return 1;
	}
	
	private String formatCaptchaKey(String captchakey){
		return "p-a-captcha-"+captchakey;
	}
	
	private String formatNumberKey(String captchakey){
		return "p-a-verify-"+captchakey;
	}
	
	private void clean(String captchakey){
		final Jedis jedis = jedisPool.getResource();
		try{
			jedis.del(formatCaptchaKey(captchakey));
			jedis.del(formatNumberKey(captchakey));
		}catch(Exception e){
			LOGGER.error(e.getMessage(),e);
		}finally{
			jedisPool.returnResource(jedis);
		}
	}
}
